package com.probiz.estore.core.security;

import java.net.URLEncoder;

import org.acegisecurity.AuthenticationException;
import org.acegisecurity.providers.cas.TicketResponse;
import org.acegisecurity.providers.cas.TicketValidator;
import org.acegisecurity.ui.cas.ServiceProperties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.TicketValidationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * CAS票据验证与SSO自配置
 * 
 */
public class ProbizTicketValidator implements TicketValidator, InitializingBean {

	protected static final Log log = LogFactory.getLog(ProbizTicketValidator.class);
	
	private static String REDIRECT_TO_CAS_URL = "";
	
	//引用到JA-SIG内置的TicketValidator
	private AbstractUrlBasedTicketValidator casValidate;
	
	private ServiceProperties serviceProperties;
	
	private String loginUrl;
	
	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public void afterPropertiesSet() throws Exception {
		Assert.notNull(this.casValidate);
		Assert.notNull(this.serviceProperties);
		Assert.notNull(this.loginUrl);
		REDIRECT_TO_CAS_URL = loginUrl + "?service=" + URLEncoder.encode(this.getServiceProperties().getService(), "UTF-8");
	}

	public TicketResponse confirmTicketValid(String serviceTicket)
			throws AuthenticationException {
		Assertion assertion = null;
		String userName = null;
		try {
			assertion = this.getCasValidate().validate(serviceTicket, this.serviceProperties.getService());
			userName = assertion.getPrincipal().getName();
		} catch (TicketValidationException e) {
			log.error(e);
			return new TicketResponse(null, null, null);
		}
		return new TicketResponse(assertion.getPrincipal().getName(), null, null);
	}

	public AbstractUrlBasedTicketValidator getCasValidate() {
		return casValidate;
	}

	public void setCasValidate(AbstractUrlBasedTicketValidator casValidate) {
		this.casValidate = casValidate;
	}

	public ServiceProperties getServiceProperties() {
		return serviceProperties;
	}
	
	public void setServiceProperties(ServiceProperties serviceProperties) {
		this.serviceProperties = serviceProperties;
	}

	public static boolean isCasEnabled(){
		return !"".equals(REDIRECT_TO_CAS_URL);
	}
	
	public static String getRedirect2CasUrl(){
		return REDIRECT_TO_CAS_URL;
	}
}